myApp.controller('uTestController', function ($scope, $rootScope, $uibModal, $stateParams, $http, ngDialog, $interval, $sce) {
    $scope.info = {};
    $scope.info.projects = [];
    $scope.info.agents = [];
    $scope.info.projectAgents = [];
    $scope.info.projectSelect = {};
    $scope.info.agentSelect = {};
    $scope.info.isLogTrue = false;
    $scope.info.isTree = false;
    $scope.info.logs = '';
    $scope.predicate = "";
    $scope.treedata = [];
    $scope.expandedNodes = [];
    $scope.info.caseIds = "";
    $scope.info.caseNames = "";
    $scope.info.tags = "";
    $scope.info.reportPath = "";
    $scope.info.isOpen = false;
    $scope.socket = null;

    $scope.closeSocket = function () {
        if ($scope.socket != null) {
            $scope.socket.close();
            $scope.socket = null;
        }
    };

    $scope.$on("$destroy", function () {
        $scope.closeSocket();
    });

    function createSubTree() {
        LoadModal($uibModal);
        $http.get(agent_url + '/autotest/getTree').success(function (data) {
            closeModal();
            $scope.treedata = data.data;
            $scope.expandedNodes.push($scope.treedata[0]);
            angular.forEach($scope.treedata[0].childs, function (node) {
                $scope.expandedNodes.push(node);
            });
            $scope.info.isTree = true;
        })
    };

    $scope.init = function () {
        $scope.info.isTree = false;
        $scope.info.isOpen = false;
        $scope.info.isLogTrue = false;
        $scope.info.logs = '';
        $scope.info.caseIds = "";
        $scope.info.caseNames = "";
        $scope.closeSocket();
    }


    $scope.treeOptions = {
        multiSelection: false,
        allowDeselect: false,
        nodeChildren: 'childs'
    };
    $scope.selectedNode = $scope.treedata[0];


    $scope.getProjects = function () {
        $http.get(beetle_plan_url + '/project_plan/getPlanList?&token_id=' + getTokenId() + '&isShowOnline=false').success(function (planDatas) {
            angular.forEach(planDatas.data, function (planData) {
                splicingProjectData(planData.plan_id, planData.plan_name)
            })
            $http.get(beetle_plan_url + '/integration/getIntegrationPlanList?token_id=' + getTokenId() + '&hasProList=false').success(function (integrationDatas) {
                angular.forEach(integrationDatas.data, function (integrationData) {
                    splicingProjectData(integrationData.integration_id, integrationData.integration_name)
                })
            })
        });

    };

    function splicingProjectData(id, name) {
        var obj = {};
        obj.id = id;
        obj.name = name;
        $scope.info.projects.push(obj)
    }

    $scope.getProjects();


    $scope.getAgents = function () {
        $http.get(ucloud_master_url + '/api/v1/agent/?token_id=' + getTokenId()).success(function (agents) {
            $scope.info.agents = agents.data;
        })
    }
    $scope.getAgents();


    $scope.projectClick = function () {
        $scope.init();
        $scope.info.projectAgents = [];
        angular.forEach($scope.info.agents, function (agent) {
            if ($scope.info.projectSelect != null && agent.plan_id == $scope.info.projectSelect.id) {
                $scope.info.projectAgents.push(agent)
            }
        })
        if ($scope.info.projectAgents.length == 0) {
            $scope.info.agentSelect = "";
            $scope.treedata = [];
        }
        $scope.closeSocket();
    }


    $scope.agentClick = function () {
        if ($scope.info.agentSelect != null) {
            createSubTree();
        } else {
            $scope.init();
        }
    }
    //点击选中事件
    $scope.checkChange = function (node) {
        console.log(node)
        if (node.is_case == "1") {
            if (node.Selected) {
                strs(node)
            } else {
                strReplace(node)
            }
        } else {
            subnodeSelect(node.childs, node.Selected)
        }
    }

    function subnodeSelect(childs, isTrue) {
        angular.forEach(childs, function (child) {
            child.Selected = isTrue;
            if (child.childs != undefined) {
                $scope.checkChange(child)
            }
            if (child.is_case == "1") {
                if (isTrue) {
                    strs(child)
                } else {
                    strReplace(child)
                }
            }
        })
    }

    function strs(node) {
        if ($scope.info.caseIds.indexOf(node.id + ",") == -1) {
            $scope.info.caseIds += node.id + ",";
            $scope.info.caseNames += node.name + ",";
        }
    }

    function strReplace(node) {
        $scope.info.caseIds = $scope.info.caseIds.replace(node.id + ",", "");
        $scope.info.caseNames = $scope.info.caseNames.replace(node.name + ",", "");
    }

    var logDiv = document.getElementById("log_div");

    function uCloudSocket() {
        var ip = $scope.info.agentSelect.agent_ip;
        if (typeof ip == 'undefined'
            || ip == 'undefined'
            || ip == '') {
            return;
        }
        ;
        $scope.closeSocket();
        $scope.socket = io.connect('http://' + ip + ':5000/notify', {'forceNew': true});
        $scope.socket.on("stat", function (msg) {
            $scope.$apply(function () {
                var obj = {};
                var message = '';
                if (msg.data.indexOf("autoTest" != -1)) {
                    console.log(msg)
                    if (msg.data.indexOf("reportPath:") != -1) {
                        $scope.info.isOpen = true;
                        obj = angular.fromJson(msg.data)
                        $scope.info.reportPath = obj.message.split(":")[1]
                        return
                    }
                    if (msg.data.indexOf("finish") != -1 || msg.data.indexOf("Connected") != -1) {
                        return
                    }
                    if (msg.data.indexOf("PASS:") != -1) {
                        message = "<span style='color: #00a65a;'>" + msg.data.slice(32, -2) + "</span>";
                    } else if (msg.data.indexOf("FAIL:") != -1 || msg.data.indexOf("ERROR:") != -1) {
                        message = "<span style='color:red;padding-left: 15px;'>" + msg.data.slice(32, -2) + "</span><br>";
                    } else {
                        message = msg.data.slice(32, -2) + "<br>";
                    }
                    $scope.info.logs = $sce.trustAsHtml($scope.info.logs + message);
                    setTimeout(function () {
                        logDiv.scrollTop = logDiv.scrollHeight;
                    }, 50);
                }


            })

        });
    };

    $scope.open = function () {
        window.open('http://' + $scope.info.agentSelect.agent_ip + ":" + uTest_port + $scope.info.reportPath)
    }


    $scope.isStart = function () {
        if ($scope.info.projectSelect != '' && $scope.info.agentSelect != '') {
            return false;
        } else {
            return true;
        }
    };
    $scope.startTesting = function () {
        openDialog(ngDialog, $scope, "确定要执行测试么?", true, function (val) {
            if (!val) {
                return;
            }
            // if ($scope.info.caseIds == "" || $scope.info.caseNames == "") {
            //     alert("请选择测试用例。");
            //     return;
            // }
            $scope.info.isOpen = false;
            $scope.info.reportPath = '';
            $scope.info.logs = '';
            var param = {
                agent_ip: $scope.info.agentSelect.agent_ip,
                plan_id: $scope.info.projectSelect.id,
                case_names: $scope.info.caseNames.length == 0 ? "" : $scope.info.caseNames.substring(0, $scope.info.caseNames.length - 1),
                agent_id: $scope.info.agentSelect.id,
                token_id: getTokenId(),
                plan_name: $scope.info.projectSelect.name
            };
            if ($scope.info.caseIds.length != 0) {
                param.case_ids = $scope.info.caseIds.substring(0, $scope.info.caseIds.length - 1);
            }
            if ($scope.info.tags.length != 0) {
                param.tags = $scope.info.tags;
            }
            $http.post(beetle_plan_url + "/autotest/do", param).success(function (data) {
                if (data.success) {
                    uCloudSocket();
                    $scope.info.isLogTrue = true;
                } else {
                    alert(data.msg)
                }
            })
        })

    }

})